package com.api.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.api.model.User;

public class UserDao extends JdbcDaoSupport implements IDao<User> {

    class UserRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            return user;
        }
    }

    @Override
    public User add(final User user) {
        final String sql = "insert into user(name) values(?)";
        KeyHolder holder = new GeneratedKeyHolder();
        SqlUpdate update = new SqlUpdate();
        update.setDataSource(getDataSource());
        update.declareParameter(new SqlParameter(Types.VARCHAR));
        update.setSql(sql);
        update.setReturnGeneratedKeys(true);
        update.setGeneratedKeysColumnNames(new String[] { "id" });
        update.compile();
        int count = update.update(new String[] { user.getName() }, holder);
        if (count > 0) {
            user.setId(holder.getKey().longValue());
            return user;
        }
        return null;
    }

    @Override
    public boolean delete(Long id) {
        int count = getJdbcTemplate().update("delete from user where id = ?", id);
        return count > 0;
    }

    @Override
    public boolean update(User user) {
        String sql = "update user set name = ? where id = ?";
        getJdbcTemplate().update(sql, new Object[] { user.getName(), user.getId() });
        return true;
    }

    @Override
    public User query(Long id) {
        String sql = "select * from user where id = ?";
        List<User> list = getJdbcTemplate().query(sql, new UserRowMapper(), id);
        return list.size() == 0 ? null : list.get(0);
    }

}
